package com.wzq.shiro.shirodemo.controller;

import com.wzq.shiro.shirodemo.Exception.ExceptionKey;
import com.wzq.shiro.shirodemo.bean.HttpResult;
import com.wzq.shiro.shirodemo.entity.User;
import com.wzq.shiro.shirodemo.service.UserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

/**
 * @author wzq
 * @date 2020/5/21
 * @DESC
 */
@RestController
@RequestMapping("auth")
public class AuthController {

    @Autowired
    private UserService userService;

    /**
     * @Author wzq
     * @Description: 登录授权
     * @Date 2020/5/21 16:19
     * @Param
     * @return
     **/
    @PostMapping("accredit")
    public HttpResult<Object> accredit(@RequestParam("mobile")String mobile, @RequestParam("pwd")String pwd) throws Exception {
        try {
            // shiro 登录
            //  1,构造登录令牌
            pwd = new Md5Hash(pwd, mobile, 3).toString();
            UsernamePasswordToken passwordToken = new UsernamePasswordToken(mobile,pwd);
            //  2,获取subject，调用login方法，进去realm完成认证
            Subject subject = SecurityUtils.getSubject();
            subject.login(passwordToken);
            //  3，获取sessionId
            String sessionId = subject.getSession().getId().toString();
            //  4，构造返回结果
            return HttpResult.success(sessionId);
        }catch (Exception e){
            return HttpResult.error(ExceptionKey.AUTHENTICATION_FAILED);
        }
    }

    @PostMapping("registered")
    public HttpResult<User> registered(@RequestBody User user){
        userService.registered(user);
        return HttpResult.success();
    }

    @GetMapping("profile")
    public HttpResult<List<User>> getProfileResult(){
        return HttpResult.success(userService.list());
    }

    @GetMapping("loginOut")
    public HttpResult loginOut(){
        return HttpResult.error("未授权");
    }

}
